package com.mikeli.javacourse.lesson1.homework;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 自定义类加载器
 */
public class HelloClassLoader extends ClassLoader {
    private String classpath;

    public HelloClassLoader(String path) {
        this.classpath = path;
    }


    public static void main(String[] args) {
        String path = "Hello.xlass";
        try {
            Class clazz = new HelloClassLoader(path).loadClass("Hello");
            Object instance = clazz.newInstance();
            for (Method method : clazz.getMethods()) {
                if (method.getName().equals("hello")) {
                    method.invoke(instance);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected Class<?> findClass(String name) {
        byte[] classByte = loadCustomClass();
        decodeClassByte(classByte);
        return defineClass(name, classByte, 0, classByte.length);
    }

    private void decodeClassByte(byte[] classByte) {
        for (int i = 0; i < classByte.length; i++) {
            classByte[i] = (byte) (255 - classByte[i]);
        }
    }

    /**
     * 加载Hello.xlass
     *
     * @return 文件的字节数组
     */
    public byte[] loadCustomClass() {
        ByteArrayOutputStream byteArrayOutputStream = null;
        InputStream in = null;
        try {

            in = this.getClass().getClassLoader().getResourceAsStream(classpath);
            byteArrayOutputStream = new ByteArrayOutputStream();
            int i = -1;
            while ((i = in.read()) != -1) {
                byteArrayOutputStream.write(i);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        throw new RuntimeException(String.format("类【%s】加载异常", classpath));
    }


}
